<template>
  <view class="category-page">
    <!-- 顶部导航（增加阴影和品牌感） -->
    <!-- <u-navbar 
      title="专业无人机商城" 
      :border="false" 
      background="#ffffff"
      title-color="#0F172A"
      title-bold
      title-size="34rpx"
      :custom-style="{ boxShadow: '0 2rpx 10rpx rgba(0, 0, 0, 0.05)' }"
    ></u-navbar> -->
    
    <!-- 新旧切换标签（增大交互区域，强化选中态） -->
    <view class="condition-tabs">
      <view 
        class="tab-item" 
        :class="{ active: condition === 'new' }"
        @click="changeCondition('new')"
      >
        <text>全新设备</text>
        <view class="tab-indicator" v-if="condition === 'new'"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: condition === 'used' }"
        @click="changeCondition('used')"
      >
        <text>二手设备</text>
        <view class="tab-indicator" v-if="condition === 'used'"></view>
      </view>
    </view>
    
    <!-- 分类内容区域（强化左右布局对比） -->
    <view class="category-container">
      <!-- 左侧分类导航（优化选中高亮效果） -->
      <scroll-view 
        class="category-nav" 
        scroll-y 
        :scroll-with-animation="true"
        :scroll-top="navScrollTop"
      >
        <view 
          class="nav-item" 
          v-for="(item, index) in categories" 
          :key="item.id"
          :class="{ active: activeCategory === item.id }"
          @click="changeCategory(item.id, index)"
        >
          <text>{{item.name}}</text>
          <view class="nav-indicator" v-if="activeCategory === item.id"></view>
        </view>
      </scroll-view>
      
      <!-- 右侧商品列表（增加内容呼吸感） -->
      <scroll-view 
        class="product-list" 
        scroll-y 
        @scroll="handleScroll"
        :scroll-top="productScrollTop"
        :scroll-with-animation="true"
      >
        <!-- 分类标题（强化层级关系） -->
        <view class="category-header">
          <view class="header-wrapper">
            <text class="category-title">{{currentCategory.name}}</text>
            <text class="category-desc">{{currentCategory.description}}</text>
          </view>
          <view class="product-count">
            <text>共 {{filteredProducts.length}} 款产品</text>
          </view>
        </view>
        
        <!-- 商品列表（优化网格布局） -->
        <view class="products-grid">
          <view 
            class="product-card" 
            v-for="(product, index) in filteredProducts" 
            :key="product.id"
            @click="viewProductDetail(product)"
            :style="{ animationDelay: `${index * 80}ms` }"
          >
            <!-- 商品标签（新增角标设计） -->
            <view class="product-tag-corner" v-if="product.tag">
              {{product.tag}}
            </view>
            
            <image 
              class="product-image" 
              :src="product.image" 
              mode="aspectFill"
              lazy-load
            ></image>
            
            <view class="product-info">
              <text class="product-name">{{product.name}}</text>
              <text class="product-spec">{{product.spec}}</text>
              
              <!-- 二手商品额外信息 -->
              <text class="product-used-info" v-if="product.condition === 'used'">
                {{product.usedInfo || '已使用'}}
              </text>
              
              <view class="product-footer">
                <text class="product-price">¥{{product.price}}</text>
                <view class="product-tag" :class="product.condition">
                  {{product.condition === 'new' ? '全新' : '二手'}}
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 空状态处理 -->
        <view class="empty-state" v-if="filteredProducts.length === 0 && !loading">
          <image src="/static/images/empty-product.png" mode="widthFix" class="empty-img"></image>
          <text class="empty-text">暂无符合条件的商品</text>
        </view>
        
        <!-- 加载更多（优化加载动效） -->
        <view class="load-more" v-if="hasMore && filteredProducts.length > 0">
          <u-loading-icon size="32" color="#1E40AF" mode="flower"></u-loading-icon>
          <text>加载更多...</text>
        </view>
        <view class="no-more" v-else-if="!hasMore && filteredProducts.length > 0">
          <text>已显示全部商品</text>
        </view>
      </scroll-view>
    </view>
	<helang-tabBar></helang-tabBar>
  </view>
</template>

<script>
import helangTabBar from '@/components/helang-tabBar/helang-tabBar.vue'
export default {
  components:{
	  helangTabBar
  },
  data() {
    return {
      condition: 'new', // 当前设备条件 new/used
      activeCategory: 0, // 当前选中分类ID
      navScrollTop: 0,   // 左侧导航滚动位置
      productScrollTop: 0, // 右侧商品滚动位置
      loading: false,    // 加载状态
      hasMore: true,     // 是否有更多数据
      pageSize: 8,       // 每页显示数量（增大每页数量，减少加载次数）
      currentPage: 1,    // 当前页码
      
      // 分类数据（去重+完善描述）
      categories: [
        { id: 0, name: '全部', description: '全品类专业无人机设备及解决方案' },
        { id: 1, name: '植保', description: '高效农业喷洒、施肥专用无人机系统' },
        { id: 2, name: '物流', description: '智能货物配送、运输无人机平台' },
        { id: 3, name: '电力', description: '线路巡检、故障排查专业设备' },
        { id: 4, name: '测绘', description: '高精度地理测绘与建模解决方案' },
        { id: 5, name: '消防', description: '应急救援、火情监测无人机' },
        { id: 6, name: '环境', description: '生态监测、污染溯源专业设备' },
        { id: 7, name: '航拍', description: '影视级高清航拍器材套装' },
        { id: 8, name: '城管', description: '城市管理、违建巡查无人机系统' }
      ],
      
      // 所有商品数据（补充更多字段）
      allProducts: [
        // 全新商品
        { id: 101, name: 'DJI Agras T40', image: 'https://picsum.photos/seed/agras1/600/600', 
          spec: '作业效率40亩/小时 | 30L药箱', price: '49,999', condition: 'new', categoryId: 1, tag: '新品' },
        { id: 102, name: '极飞P100 Pro', image: 'https://picsum.photos/seed/p100/600/600', 
          spec: '50kg载重 | 智能避障', price: '52,800', condition: 'new', categoryId: 1, tag: '热销' },
        { id: 201, name: '顺丰物流无人机X1', image: 'https://picsum.photos/seed/sf1/600/600', 
          spec: '载重10kg | 续航30分钟', price: '68,000', condition: 'new', categoryId: 2, tag: '企业专供' },
        { id: 301, name: '大疆M300 RTK', image: 'https://picsum.photos/seed/m300/600/600', 
          spec: '55分钟续航 | 双电池', price: '65,999', condition: 'new', categoryId: 3, tag: '旗舰款' },
        { id: 401, name: '华测P700测绘无人机', image: 'https://picsum.photos/seed/p700/600/600', 
          spec: '1:500比例尺 | 厘米级精度', price: '89,500', condition: 'new', categoryId: 4, tag: '新品' },
        { id: 501, name: '科比特消防无人机K8', image: 'https://picsum.photos/seed/k8/600/600', 
          spec: '搭载灭火器 | 热成像', price: '72,300', condition: 'new', categoryId: 5 },
        
        // 二手商品
        { id: 103, name: '大疆T30', image: 'https://picsum.photos/seed/t30/600/600', 
          spec: '30L药箱 | 智能规划', price: '29,999', condition: 'used', categoryId: 1, usedInfo: '95新 | 使用200小时' },
        { id: 104, name: '极飞V50', image: 'https://picsum.photos/seed/v50/600/600', 
          spec: '智能避障 | 定高飞行', price: '35,600', condition: 'used', categoryId: 1, usedInfo: '9新 | 使用50小时' },
        { id: 202, name: '京东物流无人机J1', image: 'https://picsum.photos/seed/jd1/600/600', 
          spec: '航程50km | 载重8kg', price: '52,500', condition: 'used', categoryId: 2, usedInfo: '8新 | 使用1年' },
        { id: 302, name: '极飞V40', image: 'https://picsum.photos/seed/v40/600/600', 
          spec: '红外热成像 | 变焦镜头', price: '38,800', condition: 'used', categoryId: 3, usedInfo: '9新 | 使用100小时' },
        { id: 701, name: '大疆悟2专业套装', image: 'https://picsum.photos/seed/wu2/600/600', 
          spec: 'X7相机 | 3轴稳定器', price: '42,000', condition: 'used', categoryId: 7, usedInfo: '95新 | 少用' }
      ]
    }
  },
  
  computed: {
    // 当前分类信息（增加默认值处理）
    currentCategory() {
      return this.categories.find(item => item.id === this.activeCategory) || this.categories[0]
    },
    
    // 筛选后的商品（修复"全部"分类逻辑）
    filteredProducts() {
      return this.allProducts
        .filter(product => {
          // 全部分类时不过滤categoryId
          const categoryMatch = this.activeCategory === 0 ? true : product.categoryId === this.activeCategory
          const conditionMatch = product.condition === this.condition
          return categoryMatch && conditionMatch
        })
        .slice(0, this.currentPage * this.pageSize)
    }
  },
  
  onLoad() {
    // 初始化时检查是否有更多数据
    this.checkHasMore()
    // 初始化商品动画
    this.initAnimations()
  },
  
  methods: {
    // 切换新旧条件（重置分页更流畅）
    changeCondition(condition) {
      if (this.condition === condition) return
      
      this.condition = condition
      this.currentPage = 1
      this.loading = false
      this.productScrollTop = 0
      // 重新检查是否有更多数据
      this.$nextTick(() => this.checkHasMore())
    },
    
    // 切换分类（优化滚动定位逻辑）
    changeCategory(id, index) {
      if (this.activeCategory === id) return
      
      this.activeCategory = id
      this.currentPage = 1
      this.loading = false
      this.productScrollTop = 0
      
      // 左侧导航滚动居中处理
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this)
        query.select(`.nav-item:nth-child(${index + 1})`).boundingClientRect()
        query.select('.category-nav').boundingClientRect()
        query.exec(res => {
          if (res[0] && res[1]) {
            const itemTop = res[0].top
            const navHeight = res[1].height
            const itemHeight = res[0].height
            // 计算居中位置（减去导航栏高度偏移）
            this.navScrollTop = this.navScrollTop + (itemTop - navHeight / 2 + itemHeight / 2)
          }
        })
      })
      
      // 重新检查是否有更多数据
      this.$nextTick(() => this.checkHasMore())
    },
    
    // 处理滚动加载（优化触发时机）
    handleScroll(e) {
      if (this.loading || !this.hasMore) return
      
      const { scrollHeight, scrollTop, clientHeight } = e.detail
      // 距离底部150rpx时触发加载
      if (scrollHeight - scrollTop - clientHeight < 150) {
        this.loadMore()
      }
    },
    
    // 加载更多（优化异步逻辑）
    loadMore() {
      if (this.loading || !this.hasMore) return
      
      this.loading = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        this.currentPage++
        this.checkHasMore()
        this.loading = false
      }, 800)
    },
    
    // 检查是否有更多数据（抽离逻辑，减少重复计算）
    checkHasMore() {
      const total = this.allProducts.filter(product => {
        const categoryMatch = this.activeCategory === 0 ? true : product.categoryId === this.activeCategory
        const conditionMatch = product.condition === this.condition
        return categoryMatch && conditionMatch
      }).length
      
      this.hasMore = this.currentPage * this.pageSize < total
    },
    
    // 查看商品详情（增加跳转动画）
    viewProductDetail(product) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${product.id}&title=${product.name}`,
        animationType: 'pop-in',
        animationDuration: 300
      })
    },
    
    // 初始化商品动画（兼容uni-app选择器）
    initAnimations() {
      this.$nextTick(() => {
        // 用uni的选择器替代document
        const query = uni.createSelectorQuery().in(this)
        query.selectAll('.product-card').boundingClientRect()
        query.exec(res => {
          if (res[0] && res[0].length) {
            // 延迟触发动画，增强入场感
            setTimeout(() => {
              res[0].forEach((_, index) => {
                const el = this.$refs[`productRef${index}`][0]
                if (el) {
                  el.style.opacity = '1'
                  el.style.transform = 'translateY(0)'
                }
              })
            }, 300)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/* 颜色系统升级（更显专业大气） */
$primary: #1E40AF;       // 深蓝主色（更显专业）
$primary-light: #EFF6FF; // 主色浅色背景
$success: #059669;       // 成功绿
$warning: #D97706;       // 警告金
$danger: #DC2626;        // 危险红

$text-primary: #0F172A;  // 深灰文字（更清晰）
$text-secondary: #334155; // 次要文字
$text-tertiary: #64748B; // 辅助文字

$bg-light: #F8FAFC;      // 浅色背景
$border-color: #E2E8F0;  // 边框色

/* 页面基础样式 */
.category-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $bg-light;
}

/* 新旧切换标签（增大尺寸，强化交互） */
.condition-tabs {
  display: flex;
  background-color: #FFFFFF;
  padding: 0 40rpx;
  height: 100rpx;
  align-items: center;
  
  .tab-item {
    flex: 1;
    text-align: center;
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 30rpx;
    color: $text-secondary;
    transition: color 0.3s ease;
    
    &.active {
      color: $primary;
      font-weight: 600;
    }
  }
  
  .tab-indicator {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 80rpx;
    height: 6rpx;
    background-color: $primary;
    border-radius: 3rpx;
    transition: width 0.3s ease;
  }
}

/* 分类内容容器 */
.category-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧分类导航（强化选中态） */
.category-nav {
  width: 150rpx;
  background-color: #FFFFFF;
  text-align: center;
  
  .nav-item {
    position: relative;
    padding: 36rpx 0;
    font-size: 28rpx;
    color: $text-secondary;
    transition: all 0.3s ease;
    
    &.active {
      color: $primary;
      background-color: $primary-light;
      font-weight: 600;
    }
  }
  
  .nav-indicator {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 8rpx;
    height: 40rpx;
    background-color: $primary;
    border-radius: 0 4rpx 4rpx 0;
  }
}

/* 右侧商品列表（增加内边距呼吸感） */
.product-list {
  flex: 1;
  padding: 30rpx 10rpx;
  box-sizing: border-box;
}

/* 分类标题（强化层级） */
.category-header {
  margin-bottom: 30rpx;
  
  .header-wrapper {
    margin-bottom: 15rpx;
  }
  
  .category-title {
    display: block;
    font-size: 36rpx;
    font-weight: 700;
    color: $text-primary;
    line-height: 1.3;
  }
  
  .category-desc {
    font-size: 26rpx;
    color: $text-tertiary;
    line-height: 1.4;
  }
  
  .product-count {
    font-size: 24rpx;
    color: $text-tertiary;
    padding: 8rpx 0;
    border-top: 1px solid $border-color;
  }
}

/* 商品网格布局（优化间距） */
.products-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
  margin-bottom: 40rpx;
}

/* 商品卡片（提升精致度） */
.product-card {
  background-color: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.04);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  opacity: 0;
  transform: translateY(40rpx);
  position: relative;
  
  &:hover {
    box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.08);
    transform: translateY(-5rpx);
  }
  
  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
  }
  
  .product-tag-corner {
    position: absolute;
    top: 15rpx;
    left: 15rpx;
    background-color: $primary;
    color: #FFFFFF;
    font-size: 22rpx;
    padding: 6rpx 14rpx;
    border-radius: 6rpx;
    z-index: 2;
    font-weight: 500;
  }
  
  .product-image {
    width: 100%;
    height: 320rpx;
    background-color: #F1F5F9;
    border-radius: 20rpx 20rpx 0 0;
  }
  
  .product-info {
    padding: 24rpx;
    
    .product-name {
      display: block;
      font-size: 30rpx;
      font-weight: 600;
      color: $text-primary;
      margin-bottom: 10rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      line-height: 1.3;
    }
    
    .product-spec {
      display: block;
      font-size: 24rpx;
      color: $text-tertiary;
      margin-bottom: 15rpx;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .product-used-info {
      display: block;
      font-size: 22rpx;
      color: $warning;
      margin-bottom: 15rpx;
      padding: 4rpx 0;
    }
    
    .product-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10rpx;
      
      .product-price {
        font-size: 30rpx;
        font-weight: 700;
        color: $danger;
        line-height: 1;
      }
      
      .product-tag {
        font-size: 22rpx;
        padding: 6rpx 16rpx;
        border-radius: 20rpx;
        font-weight: 500;
        
        &.new {
          background-color: rgba($success, 0.1);
          color: $success;
        }
        
        &.used {
          background-color: rgba($warning, 0.1);
          color: $warning;
        }
      }
    }
  }
}

/* 加载状态样式优化 */
.load-more, .no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  font-size: 26rpx;
  color: $text-tertiary;
  
  .u-loading-icon {
    margin-right: 15rpx;
  }
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  
  .empty-img {
    width: 240rpx;
    margin-bottom: 30rpx;
    opacity: 0.7;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: $text-tertiary;
  }
}

/* 商品入场动画 */
@keyframes productFadeIn {
  from {
    opacity: 0;
    transform: translateY(40rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.product-card {
  animation: productFadeIn 0.5s ease-out forwards;
}
</style>